package com.ketangpai.admin.service.impl;

import com.ketangpai.admin.dao.SectionDao;
import com.ketangpai.admin.entity.dto.SectionDTO;
import com.ketangpai.admin.service.SectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SectionServiceImpl implements SectionService {

    private SectionDao sectionDao;

    @Autowired
    public SectionServiceImpl(SectionDao sectionDao) {
        this.sectionDao = sectionDao;
    }

    @Override
    public List<SectionDTO> getAllDirectories() {
        List<SectionDTO>  sectionDaoAll = sectionDao.findAll();
        List<SectionDTO> sectionDTOList = sectionDaoAll.stream()
                .filter(sectionDTO -> sectionDTO.getParentKey() == null).collect(Collectors.toList());
        return this.buildInfoTree(sectionDTOList,sectionDaoAll);
    }

    @Override
    public List<SectionDTO> getByParentId(Integer parentId) {
        List<SectionDTO> sectionDaoAll = sectionDao.findAll();
        List<SectionDTO> sectionDTOList = (List<SectionDTO>) sectionDao.findByParentId(parentId);
        return this.buildInfoTree(sectionDTOList,sectionDaoAll);
    }
    private List<SectionDTO> buildInfoTree(List<SectionDTO> infoDTOList, List<SectionDTO> allInfo) {
        // 遍历所有
        infoDTOList.forEach(sectionDTO -> {
            List<SectionDTO> chileInfoDTOList = sectionDTO.getSections();

            allInfo.forEach(childCodeTableInfoDTO -> {
                // 判断关系
                if (childCodeTableInfoDTO.getParentKey() != null &&
                        childCodeTableInfoDTO.getParentKey().equals(sectionDTO.getSonKey())) {
                    chileInfoDTOList.add(childCodeTableInfoDTO);
                }

            });
            // 递归构建树
            buildInfoTree(chileInfoDTOList, allInfo);
        });
        return infoDTOList;
    }

}
